$(function () {
    //初始化加载
    var str = ``
    var page = 1
    if (page = 1) {
        localStorage.setItem('searchShopping', JSON.stringify([]))
    }
    var pageSize = 4
    let shoppingContext = JSON.parse(localStorage.getItem('searchContext'))
    //获取商品列表
    let shoppings = JSON.parse(localStorage.getItem('searchShopping')) || []
    //下拉刷新
    mui.init({
        pullRefresh: {
            container: "#refreshContainer",//下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
            up: {
                height: 50,//可选,默认50.触发下拉刷新拖动距离,
                auto: true,
                contentrefresh: "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
                contextnomore: '没有更多的商品了...',
                callback: downFlesh //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
            }
            // down: {
            //     height: 50,//可选,默认50.触发下拉刷新拖动距离,
            //     contentdown: "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
            //     auto: true,//可选,默认false.首次加载自动下拉刷新一次
            //     contentrefresh: "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
            //     callback: () => {
            //         str = ''
            //         page = 1
            //         localStorage.setItem('searchShopping', JSON.stringify([]))
            //         $.ajax({
            //             type: 'GET',
            //             url: '/product/queryProduct',
            //             data: {
            //                 proName: shoppingContext,
            //                 page: page++,
            //                 pageSize
            //             },
            //             success: (result) => {
            //                 setTimeout(() => {
            //                     if (result) {
            //                         if (result.error) {
            //                             mui.toast(result.message)
            //                         } else {
            //                             if (result.data.length > 0) {
            //                                 localStorage.setItem('searchShopping', JSON.stringify(result.data))
            //                                 shoppings = JSON.parse(localStorage.getItem('searchShopping'))
            //                                 initShopping(str, shoppings)
            //                             } else {
            //                                 mui('#refreshContainer').pullRefresh().pullupLoading();
            //                             }

            //                         }
            //                     } else {
            //                         mui.toast('无法访问服务,请联系wx:13278865643')
            //                         getLocalHistory()
            //                     }
            //                     mui('#refreshContainer').pullRefresh().pullupLoading();
            //                 }, 1000)
            //             }
            //         })


            //     } //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据
            // }
        }
    })

    //下拉加载商品
    // function upFlesh() {
    //     let that = this

    //     // setTimeout(function () { //三秒后执行函数
    //     //     window.location.reload();//刷新
    //     //     mui('#refreshContainer').pullRefresh().endPulldownToRefresh(); //用来停止刷新
    //     // }, 2000)
    // }

    //下拉加载商品
    function downFlesh() {
        let that = this
        $.ajax({
            type: 'GET',
            url: '/product/queryProduct',
            data: {
                proName: shoppingContext,
                page: page++,
                pageSize
            },
            success: (result) => {
                if (result) {
                    if (result.error) {
                        mui.toast(result.message)
                    } else {
                        if (result.data.length > 0) {
                            if (shoppings.length === 0) {
                                localStorage.setItem('searchShopping', JSON.stringify(result.data))
                            } else {
                                localStorage.setItem('searchShopping', JSON.stringify([...shoppings, ...result.data]))
                            }
                            shoppings = JSON.parse(localStorage.getItem('searchShopping'))
                            initShopping(str, shoppings)
                            that.endPullupToRefresh(false)
                        } else {
                            initShopping(str, shoppings)
                            that.endPullupToRefresh(true)
                        }

                    }
                } else {
                    mui.toast('无法访问服务,请联系wx:13278865643')
                    getLocalHistory()
                }
            }
        })
    }

    //初始化加载
    function initShopping(str, shoppings) {
        //获取本地购物车
        let shopCart = JSON.parse(localStorage.getItem('shopCart')) || []
        console.log(shoppings)
        if (shoppings.length === 0) {
            str = '<p style="text-align:center;">未搜索到相关产品...</p>'
        } else {
            for (let s in shoppings) {
                let shopClass = ''
                if (shopCart.length !== 0) {
                    for (let i in shopCart) {
                        if (parseInt(shopCart[i]) === shoppings[s].id) {
                            shopClass = 'activeShopping'
                        }
                    }
                }

                str += `
                <li class="mui-table-view-cell mui-media mui-col-xs-6">
                    <a href="#">
                        <img class="mui-media-object" src="${shoppings[s].pic[0].picAddr}">
                        <div class="mui-media-body"><span>${shoppings[s].proName}</span></div>
                        <div class="maker">
                            <span class="price">￥: ${shoppings[s].price}</span>
                            <button id="goShop" type="button" class="mui-btn mui-btn-danger"  data-id="${shoppings[s].id}">购买</button>
                            <span class="fa fa-star-o addShopCar ${shopClass}" aria-hidden="true" data-id="${shoppings[s].id}"></span>
                        </div>
                    </a>
                </li>
            `
            }
        }
        let timer = setTimeout(() => {
            $('.shoppings').html(str)
            clearTimeout(timer)
        }, 400);
    }

    //购物车加入和移除商品
    $(document).on('tap', '.addShopCar', (e) => {
        //商品id
        let id = e.currentTarget.dataset.id
        //获取本地购物车
        let shopCart = JSON.parse(localStorage.getItem('shopCart')) || []
        //判断购物车是否已有次商品
        if (shopCart.length !== 0) {
            for (let s in shopCart) {
                if (shopCart[s] === id) {
                    $(e.target).removeClass('activeShopping')
                    localStorage.setItem('shopCart', JSON.stringify(shopCart.filter(item => item != id)))
                    return
                }
            }
            $(e.target).addClass('activeShopping')
            shopCart.push(id)
            localStorage.setItem('shopCart', JSON.stringify(shopCart))
        } else {
            $(e.target).addClass('activeShopping')
            shopCart.push(id)
            localStorage.setItem('shopCart', JSON.stringify(shopCart))
        }

    })

    //点击购买功能
    $(document).on('tap', '#goShop', (e) => {
        localStorage.setItem('shoppingCurrent', {})
        let id = e.currentTarget.dataset.id
        for (let s in shoppings) {
            if (shoppings[s].id === parseInt(id)) {
                localStorage.setItem('shoppingCurrent', JSON.stringify(shoppings[s]))
                window.location.href = '/shoppingCurrent'
            }
        }
    })
})





